package chen.web.back.client.post;

import java.util.ArrayList;
import java.util.List;

import chen.web.back.client.FormDataBuilder;
import chen.web.back.client.UrlHelper;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.tips.QuickTip;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;  

public class SubjectCheckingPanel extends LayoutContainer {

	private static final int Limit = 20;	//每页显示记录数量
	
	@Override
	protected void onRender(Element parent, int index) {
		// TODO Auto-generated method stub
		super.onRender(parent, index);
		VerticalPanel vp = new VerticalPanel();
		vp.add(createTablePanel());
		add(vp);
	}
	
	private static class TopicInfo extends BaseModelData {
			
		public int getId(){
			return get("id");
		}
		public void setId(int id){
			set("id", id);
		}
		  public String getTitle() {
		    return get("title");
		  }

		  public void setTitle(String title) {
		    set("title", title);
		  }
		  
		  public void setCategory(String category){
			  set("category", category);
		  }
		  public String getCategory(){
			  return get("category");
		  }
		  public String getAuthor(){
			  return get("author");
		  }
		  public void setAuthor(String author){
			  set("author",author);
		  }
		  public void setViewCount(int viewCount){
			  set("viewCount", viewCount);
		  }
		  public long getViewCount(){
			  return get("hits");
		  }
		  //命中率
		  public void setReplyCount(String replyCount){
			set("replyCount", replyCount);  
		  }
		  public String getReplyCount(){
			  return get("replyCount");
		  }
		  public void setLastReplier(String lastReplier){
			  set("lastReplier", lastReplier);  
		  }
		  public String getLastReplier(){
			  return get("lastReplier");  
		  }
		  public void setLink(String link){
			  set("link",link);
		  }
		  public String getLink(){
			  return get("link");
		  }
		}
	
	private void loadTopicInfo(PagingLoadConfig config, final AsyncCallback<PagingLoadResult<TopicInfo>> callback){
		int page = (config.getOffset()/config.getLimit()) + 1;
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, UrlHelper.toAbsolute("/checking/topic/forum?page=") + page);
		try{
			builder.sendRequest(null, new RequestCallback(){

				@Override
				public void onError(Request arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					displayError("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request arg0, Response response) {
					// TODO Auto-generated method stub
					if (200 == response.getStatusCode()) {
						JSONValue json = JSONParser.parseStrict(response
								.getText()).isObject().get("returnObject");
						JSONArray array = json.isObject().get("topicInfoList").isArray();
						ArrayList<TopicInfo> list = new ArrayList<TopicInfo>();
						for(int i=0; i<array.size(); i++){
							JSONObject infoObj = array.get(i).isObject();
							String title = infoObj.get("title").isString().stringValue();
							int id = (int)infoObj.get("id").isNumber().doubleValue();
							boolean digest = infoObj.get("digest").isBoolean().booleanValue();
							boolean top = infoObj.get("top").isBoolean().booleanValue();
							String category = infoObj.get("category").isObject().get("name").isString().stringValue();
							String authorName = infoObj.get("authorNickame").isString().stringValue();
							//int authorId = (int)infoObj.get("authorId").isNumber().doubleValue();
							int replyCount = (int)infoObj.get("replyCount").isNumber().doubleValue();
							int viewCount = (int)infoObj.get("viewCount").isNumber().doubleValue();
							String lastReplierNickname = infoObj.get("lastReplierNickname").isString().stringValue();
							//int lastReplierId = (int)infoObj.get("lastReplierId").isNumber().doubleValue();
							
							if(digest){
								title = title + "[<span style=\"color:red\">精华</span>]";
							}
							if(top){
								title = title + "[<span style=\"color:red\">置顶</span>]";
							}
							String link = "<a href=\"" + UrlHelper.toAbsolute("/topic/" + id) + "\" target=\"_blank\">" + "查看" + "</a>";
							
							TopicInfo info = new TopicInfo();
							info.setId(id);
							info.setTitle(title);
							info.setCategory(category);
							info.setAuthor(authorName);
							info.setReplyCount(replyCount + "/" + viewCount);
							info.setLastReplier(lastReplierNickname);
							info.setLink(link);
							list.add(info);
						}
						JSONObject pagination = json.isObject().get("pagination").isObject();
						int total = (int)pagination.get("infoAmount").isNumber().doubleValue();
						int offset = (int)pagination.get("beginOffset").isNumber().doubleValue();
						
			        	PagingLoadResult<TopicInfo> result = new BasePagingLoadResult<TopicInfo>(list);
			        	result.setOffset(offset);
			        	result.setTotalLength(total);
			        	callback.onSuccess(result);
					} else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			displayError("Couldn't retrieve JSON");
		}
	}
	
	private void operate(int[] idArray, String action){
		StringBuffer ids = new StringBuffer();
		for(int id : idArray){
			ids.append(id).append("_");
		}
		if(ids.length()>0){ids.deleteCharAt(ids.length()-1);}
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, UrlHelper.toAbsolute("/recycle-bin/topic/" +ids.toString() + "/" + action));
		builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
		try{
			FormDataBuilder data = new FormDataBuilder();
			builder.sendRequest(data.toQueryString(), new RequestCallback(){
				@Override
				public void onError(Request arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					displayError("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request arg0, Response response) {
					// TODO Auto-generated method stub
					if (200 == response.getStatusCode()) {
						boolean success = JSONParser.parseStrict(response
								.getText()).isObject().get("success").isBoolean().booleanValue();
						if(!success){
							displayError("操作失败");
						}else{
							MessageBox.alert("成功", "操作成功", null);
						}
						toolBar.refresh();
					} else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			displayError("Couldn't retrieve JSON");
		}
	}

	private final PagingToolBar toolBar = new PagingToolBar(Limit);  
	private ContentPanel createTablePanel(){ 
	    RpcProxy<PagingLoadResult<TopicInfo>> proxy = new RpcProxy<PagingLoadResult<TopicInfo>>() {  
	        @Override  
	        public void load(Object loadConfig, AsyncCallback<PagingLoadResult<TopicInfo>> callback) {  	        
	        	PagingLoadConfig config = (PagingLoadConfig)loadConfig;
	        	loadTopicInfo(config, callback);
	        }  
	      };  
	    // loader  
	    final PagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(  
	          proxy);
		ListStore<TopicInfo> store = new ListStore<TopicInfo>(loader);
	    
	    toolBar.bind(loader);
		
	    List<ColumnConfig> columns = new ArrayList<ColumnConfig>();  
	    
	    final CheckBoxSelectionModel<TopicInfo> sm = new CheckBoxSelectionModel<TopicInfo>();  
	    columns.add(sm.getColumn());
	    columns.add(new ColumnConfig("title", "标题", 360));  
	    columns.add(new ColumnConfig("category", "栏目", 80));   
	    columns.add(new ColumnConfig("replyCount", "回复/查看", 80));
	    columns.add(new ColumnConfig("author", "作者", 100));  
	    columns.add(new ColumnConfig("lastReplier", "最后回复", 100));
	    columns.add(new ColumnConfig("link", "查看", 40));
	    
		ColumnModel cm = new ColumnModel(columns);  
		
		cp = new ContentPanel();  
	    cp.setHeading("缓存列表");  
	    cp.setFrame(true);  
	    cp.setWidth(800);  
	    cp.setLayout(new FitLayout());  

	    grid = new Grid<TopicInfo>(store, cm);
	    grid.setSelectionModel(sm);  
	    grid.setBorders(true);  
	    grid.setColumnReordering(true);  
	    grid.getAriaSupport().setLabelledBy(cp.getHeader().getId() + "-label");  
	    grid.addPlugin(sm);  
	    
	    cp.add(grid);
	    cp.setBottomComponent(toolBar);  
	    
	    cp.setButtonAlign(HorizontalAlignment.CENTER);
	    cp.addButton(new Button("通过审核", new SelectionListener<ButtonEvent>() {
	      @Override
	      public void componentSelected(ButtonEvent ce) {
	    	  List<TopicInfo> list = sm.getSelectedItems();
	    	  int[] idArray = new int[list.size()];
	    	  for(int i=0;i<list.size(); i++){
	    		  idArray[i] = list.get(i).getId();
	    	  }
	    	  operate(idArray, "restore");
	      }
	    }));
	    
	    grid.addListener(Events.ViewReady, new Listener<ComponentEvent>() {
	        public void handleEvent(ComponentEvent be) {
	            grid.getStore().addListener(Store.DataChanged, new Listener<StoreEvent<TopicInfo>>() {
	                public void handleEvent(StoreEvent<TopicInfo> be) {
	                  doAutoHeight();
	                }
	              });
	              doAutoHeight();
	        }
	    });
	    PagingLoadConfig config = new BasePagingLoadConfig();  
	    config.setOffset(0);  
        config.setLimit(Limit);
        loader.load(config); 
	    return cp;
	}
	  private Grid<TopicInfo> grid;
	  private ContentPanel cp;
	  protected void doAutoHeight() {
		    if (grid.isViewReady()) {
		      grid.getView().getScroller().setStyleAttribute("overflowY", "hidden");
		      cp.setHeight((grid.getView().getBody().isScrollableX() ? 19 : 0) + grid.el().getFrameWidth("tb")
		          + grid.getView().getHeader().getHeight() + cp.getFrameHeight()
		          + grid.getView().getBody().firstChild().getHeight());
		    }
	  }
	
	
	  
	private void displayError(String message){
		MessageBox.alert("出错", message, null);
	}
	
}
